
package com.example.myjavafx.controller;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.Bounds;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * @author admin
 */
public class ImageViewController2 extends Application {
    private ImageView imageView;
    private Rectangle cropRect;
    private double startX, startY;
    private File selectedFile;

    @Override
    public void start(Stage primaryStage) {
        VBox root = new VBox(10);
        root.setPadding(new Insets(10));

        // 上传按钮
        Button uploadBtn = new Button("选择图片");
        uploadBtn.setOnAction(this::handleUpload);

        // 裁剪按钮
        Button cropBtn = new Button("执行裁剪");
        cropBtn.setOnAction(this::handleCrop);

        // 图片显示区域
        imageView = new ImageView();
        imageView.setPreserveRatio(true);
        imageView.setFitWidth(600);
        imageView.setFitHeight(400);

        StackPane imageContainer = new StackPane(imageView);
        imageContainer.setStyle("-fx-background-color: #eee;");

        // 初始化裁剪矩形
        initCropRectangle(imageContainer);

        root.getChildren().addAll(uploadBtn, imageContainer, cropBtn);
        primaryStage.setScene(new Scene(root, 800, 600));
        primaryStage.setTitle("JavaFX 图片裁剪");
        primaryStage.show();
    }

    private void initCropRectangle(StackPane container) {
        cropRect = new Rectangle();
        cropRect.setFill(Color.color(0, 0, 0, 0.2));
        cropRect.setStroke(Color.BLUE);
        cropRect.setStrokeWidth(2);
        cropRect.setVisible(false);

        container.getChildren().add(cropRect);

        // 鼠标事件处理
        container.setOnMousePressed(e -> {
            if (imageView.getImage() == null) {
                return;
            }
            startX = e.getX();
            startY = e.getY();
            cropRect.setX(startX);
            cropRect.setY(startY);
            cropRect.setWidth(0);
            cropRect.setHeight(0);
            cropRect.setVisible(true);
        });

        container.setOnMouseDragged(e -> {
            if (!cropRect.isVisible()) {
                return;
            }
            double currentX = e.getX();
            double currentY = e.getY();

            cropRect.setWidth(Math.abs(currentX - startX));
            cropRect.setHeight(Math.abs(currentY - startY));
            cropRect.setX(Math.min(startX, currentX));
            cropRect.setY(Math.min(startY, currentY));
        });
    }

    private void handleUpload(ActionEvent event) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择图片文件");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("图片文件", "*.png", "*.jpg", "*.jpeg")
        );
        selectedFile = fileChooser.showOpenDialog(null);

        if (selectedFile != null) {
            Image image = new Image(selectedFile.toURI().toString());
            imageView.setImage(image);
            cropRect.setVisible(false);
        }
    }

    private void handleCrop(ActionEvent event) {
        if (selectedFile == null || !cropRect.isVisible()) {
            return;
        }

        try {
            // 计算实际裁剪坐标（考虑图片缩放）
            Image image = imageView.getImage();
            Bounds viewBounds = imageView.getBoundsInParent();
            double scaleX = image.getWidth() / viewBounds.getWidth();
            double scaleY = image.getHeight() / viewBounds.getHeight();

            int x = (int)(cropRect.getX() * scaleX);
            int y = (int)(cropRect.getY() * scaleY);
            int width = (int)(cropRect.getWidth() * scaleX);
            int height = (int)(cropRect.getHeight() * scaleY);

            // 发送到后端
            sendToBackend(selectedFile, x, y, width, height);
        } catch (Exception e) {
            e.printStackTrace();
            showAlert("错误", "裁剪操作失败: " + e.getMessage());
        }
    }

    // HTTP请求示例
    private void sendToBackend(File imageFile, int x, int y, int width, int height) {
        try {
            // 创建多部分请求
            HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:8080/api/crop").openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            String boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            try (OutputStream output = connection.getOutputStream();
                 PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8), true)) {

                // 添加文件部分
                writer.append("--" + boundary).append("\r\n");
                writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + imageFile.getName() + "\"").append("\r\n");
                writer.append("Content-Type: image/" + getFileExtension(imageFile)).append("\r\n\r\n");
                writer.flush();

                Files.copy(imageFile.toPath(), output);
                output.flush();

                // 添加裁剪参数
                writer.append("\r\n--" + boundary).append("\r\n");
                writer.append("Content-Disposition: form-data; name=\"cropData\"").append("\r\n\r\n");
                writer.append(String.format("x=%d&y=%d&width=%d&height=%d", x, y, width, height));

                writer.append("\r\n--" + boundary + "--").append("\r\n");
            }

            // 处理响应
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                try (InputStream input = connection.getInputStream()) {
                    Files.copy(input, Paths.get("cropped_result.png"), StandardCopyOption.REPLACE_EXISTING);
                    showAlert("成功", "图片已保存为 cropped_result.png");
                }
            } else {
                showAlert("错误", "服务器返回错误: " + responseCode);
            }
        } catch (Exception e) {
            showAlert("错误", "网络请求失败: " + e.getMessage());
        }
    }

    private String getFileExtension(File file) {
        String name = file.getName();
        int lastIndexOf = name.lastIndexOf(".");
        if (lastIndexOf == -1) {
            return "";
        }
        return name.substring(lastIndexOf + 1);
    }

    private void showAlert(String title, String content) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
